package com.xzz.mq.listener;

import com.alibaba.fastjson.JSON;
import com.xzz.domain.CourseOrder;
import com.xzz.domain.PayFlow;
import com.xzz.domain.PayOrder;
import com.xzz.dto.Order2PayOrderParamDto;
import com.xzz.dto.PayResultDto;
import com.xzz.service.IPayOrderService;
import com.xzz.util.AssertUtil;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;

//支付单以及支付流水的事务消息
@Component
@RocketMQTransactionListener(txProducerGroup = "TxPayResultListener")
public class PayTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IPayOrderService payOrderService;

    //执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object args) {

        try {
            AssertUtil.isNotNull(args,"支付数据为空");
            Map<String,Object> map = (Map) args;
            PayOrder payOrder = (PayOrder)map.get("payOrder");
            PayFlow payFlow = (PayFlow)map.get("payFlow");
            payOrderService.updatePayOrderAndInsertPayFlow(payOrder,payFlow);
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            e.printStackTrace();
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }

    //检查本地事务
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] bytes = (byte[]) message.getPayload();
            String orderJSON = new String(bytes, StandardCharsets.UTF_8);
            PayResultDto payResultDto = JSON.parseObject(orderJSON, PayResultDto.class);
            //根据订单号查询订单
            PayOrder payOrder = payOrderService.selectByOrderNo(payResultDto.getOrderNo());
            if(payOrder != null){
                return RocketMQLocalTransactionState.COMMIT;
            }else {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}